package com.yao.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.mall.common.ErrorCode;
import com.yao.mall.common.IdRequest;
import com.yao.mall.common.UserHolder;
import com.yao.mall.config.BusinessException;
import com.yao.mall.mapper.*;
import com.yao.mall.model.dto.shoppingCart.ShoppingCartAddRequest;
import com.yao.mall.model.dto.shoppingCart.ShoppingCartUpdateRequest;
import com.yao.mall.model.entity.*;
import com.yao.mall.model.vo.ShoppingCartVO;
import com.yao.mall.model.vo.UserVO;
import com.yao.mall.service.ShoppingCartService;
import com.yao.mall.service.SkuAttrValueService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @author jiahua.yao
 * @description 针对表【shopping_cart】的数据库操作Service实现
 * @date 2024-03-26 19:31:12
 */
@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {

    @Resource
    private GoodsSkuMapper goodsSkuMapper;

    @Resource
    private SkuAttrValueService skuAttrValueService;

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Resource
    private SkuImageMapper skuImageMapper;


    @Override
    public Boolean addGoodsToCart(ShoppingCartAddRequest cartAddRequest) {
        UserVO user = UserHolder.getUser();
        Integer quantity = cartAddRequest.getQuantity();
        Long skuId = cartAddRequest.getSkuId();
        if (skuId == null || quantity == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1、先查询一下这个用户的购物车中是否有这个商品的数据
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        shoppingCartQueryWrapper.eq("user_id", user.getId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCartQueryWrapper);
        for (ShoppingCart shoppingCart : shoppingCarts) {
            if (!skuId.equals(shoppingCart.getSkuId())) {
                continue;
            }
            //1.1 存在，数据更新返回
            shoppingCart.setId(shoppingCart.getId());
            //数量为之前的购物车的数量加此次的数量
            shoppingCart.setQuantity(quantity + shoppingCart.getQuantity());
            shoppingCartMapper.updateById(shoppingCart);
            return true;
        }
        //2.通过sku表拿具体sku信息
        GoodsSku goodsSku = goodsSkuMapper.selectById(skuId);
        //3、存入商品表
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(user.getId());
        shoppingCart.setSkuId(skuId);
        shoppingCart.setGoodsName(goodsSku.getGoodsName());
        shoppingCart.setQuantity(quantity);
        BigDecimal skuPrice = goodsSku.getSkuPrice();
        shoppingCart.setUnitPrice(skuPrice);
        shoppingCart.setTotalPrice(skuPrice.multiply(BigDecimal.valueOf(quantity)));
        QueryWrapper<SkuImage> skuImageQueryWrapper = new QueryWrapper<>();
        skuImageQueryWrapper.eq("sku_id", goodsSku.getId());
        List<SkuImage> skuImages = skuImageMapper.selectList(skuImageQueryWrapper);
        //sku的第一张图片作为加入购物车时显示的图片
        shoppingCart.setSkuImage(skuImages.get(0).getImage());
        return this.save(shoppingCart);
    }

    @Override
    public List<ShoppingCartVO> getShoppingCart() {
        UserVO user = UserHolder.getUser();
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        shoppingCartQueryWrapper.eq("user_id", user.getId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectList(shoppingCartQueryWrapper);
        return this.toShoppingCartVO(shoppingCarts);
    }
    @Override
    public List<ShoppingCartVO> toShoppingCartVO(List<ShoppingCart> shoppingCarts) {
        return shoppingCarts.stream().map(shoppingCart -> {
            ShoppingCartVO shoppingCartVO = new ShoppingCartVO();
            BeanUtils.copyProperties(shoppingCart, shoppingCartVO);
            String attrsText = skuAttrValueService.getAttrsText(shoppingCart.getSkuId());
            //sku库存
            GoodsSku goodsSku = goodsSkuMapper.selectById(shoppingCart.getSkuId());
            shoppingCartVO.setStock(goodsSku.getStock());
            //selected转化类型
            boolean selected = shoppingCart.getSelected() != 0;
            shoppingCartVO.setSelected(selected);
            shoppingCartVO.setAttrsText(attrsText);
            return shoppingCartVO;
        }).toList();
    }

    @Override
    public Boolean updateCartGoods(ShoppingCartUpdateRequest cartUpdateRequest) {
        UserVO user = UserHolder.getUser();
        Long userId = user.getId();
        Long skuId = cartUpdateRequest.getSkuId();
        Integer quantity = cartUpdateRequest.getQuantity();
        Boolean selectedB = cartUpdateRequest.getSelected();
        if (skuId == null || quantity == null || selectedB == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "必要参数不能为空");
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        //1.注意加购数量溢出
        GoodsSku goodsSku = goodsSkuMapper.selectById(skuId);
        Integer stock = goodsSku.getStock();
        if (quantity > stock) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "商品库存数量不足");
        }
        if (quantity <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "数量已经是最小");
        }
        //2.只能够修改加购的数量，其他数据改不了。注意：总价也会变
        int selected = Boolean.TRUE.equals(selectedB) ? 1 : 0;
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        shoppingCartQueryWrapper.eq("user_id", userId).eq("sku_id", skuId);
        shoppingCart.setQuantity(quantity);
        shoppingCart.setSelected(selected);
        shoppingCart.setTotalPrice(goodsSku.getSkuPrice().multiply(BigDecimal.valueOf(quantity)));
        return this.update(shoppingCart, shoppingCartQueryWrapper);
    }


    @Override
    public Boolean deleteCartGoods(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        UserVO user = UserHolder.getUser();
        QueryWrapper<ShoppingCart> shoppingCartVOQueryWrapper = new QueryWrapper<>();
        shoppingCartVOQueryWrapper.eq("user_id", user.getId())
                .in("sku_id", ids);
        int delete = shoppingCartMapper.delete(shoppingCartVOQueryWrapper);
        return delete > 0;
    }

    @Override
    public Boolean addGoodsListToCart(List<ShoppingCartAddRequest> cartAddRequestList) {
        for (ShoppingCartAddRequest shoppingCartAddRequest : cartAddRequestList) {
            Boolean aBoolean = this.addGoodsToCart(shoppingCartAddRequest);
            if (Boolean.FALSE.equals(aBoolean)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "批量添加商品失败");
            }
        }
        return true;
    }


}




